package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"house/models"
)

type HouseController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *HouseController) Add() {
	street := c.GetString("street")
	name := c.GetString("name")
	num, _ := c.GetInt("num")
	number, _ := c.GetInt("number")
	hx := c.GetString("hx")
	price, _ := c.GetFloat("price")
	area := c.GetString("area")
	zj := c.GetString("zj")
	house := models.House{
		Street: street,
		Name:   name,
		Num:    num,
		Number: number,
		Hx:     hx,
		Price:  price,
		Area:   area,
		Zj:     zj,
	}

	if street == "" || name == "" || num == 0 || number == 0 || hx == "" || price == 0 || area == "" || zj == "" {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "以上都是必填项",
			Data: nil,
		}
		c.ServeJSON()
	}

	err := models.DB.Create(&house).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: house,
		}
		c.ServeJSON()
	}
}

func (c *HouseController) List() {
	name := c.GetString("name")
	where := make(map[string]interface{})
	if name != "" {
		where["name"] = name
	}
	var house []models.House
	err := models.DB.Find(&house).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: house,
		}
		c.ServeJSON()
	}
}

func (c *HouseController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("ID=?", id).Delete(&models.House{}).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
